var marked=require('marked');
var Comment=require('../lib/mongo').Comment;

//将comment的content从markdown转换为html
Comment.plugin('contenntToHtml',{
    afterFind:function(comments){
        return comments.map(function(comment){
            comment.content=marked(comment.content);
            return comment
        })
    }
})

module.exports={
    //创建一个留言
    create:function create(comment){
        return Comment.create(comment).exec();
    },
    //通过文章id和留言id删除一个留言
    delCommentById:function delCommentById(commentId,author){
        return Comment.remove({author:author,_id:commentId}).exec();
    },

    //通过文章id删除该文章下所有留言
    delCommentByPostId:function delCommentByPostId(postId){
        return Comment.remove({postId:postId}).exec();
    },

    //通过文章id获取该文章下所有留言，按照留言创建事件升序
    getComments:function getComments(postId){
        return Comment 
            .find({postId:postId})
            .populate({path:'author',module:'User'})
            .sort({_id:1})
            .addCreatedAt()
            .contentToHtml()
            .exex();
    },
    //通过文章id或i去问下留言数
    getCommentsCount:function getCommentsCount(postId){
        return Comment.count({postId:postId}).exec();
    }

}